#!/user/bin/env python3
# -*- coding: utf-8 -*-
"""
--------------------------------------
    Author:     JiChao_Song
    Date  :     2020/12/14 9:13
    Desc  :
--------------------------------------
"""
from common.libs.JsonResponseUtils import JsonResponse
from common.libs.PhoneCheckUtils import PhoneCheckUtils
from common.libs.paginationUtils import ListPaginationUtils
from common.libs.queryListUtils import QueryListUtils

from servers.models.userModel import User
from servers.servers.BaseServices import BaseServices


class UserServices(BaseServices):

    def __init__(self, document = User):
        super().__init__(document)


def add_valid_user(admin: int, **kwargs):
    """
    新增用户验证user
    :param form
    :return:
    """
    if kwargs.get("username") is None or kwargs.get("username") == "":
        return JsonResponse(code = 40002, data = None, message = "username不能为空").jsonExit()
    if kwargs.get('phone') is None or kwargs.get("phone") == '':
        return JsonResponse(code = 40002, data = None, message = "phone不能为空").jsonExit()
    if not PhoneCheckUtils(kwargs.get('phone')).phone_check():
        return JsonResponse(code = 40006, data = None, message = "手机号格式错误").jsonExit()
    if User.objects(username = kwargs.get("username"), admin = admin).count() != 0:
        return JsonResponse(code = 40003, data = None, message = "用户名已存在").jsonExit()
    if User.objects(phone = kwargs.get("phone"), admin = admin).count() != 0:
        return JsonResponse(code = 40003, data = None, message = "手机号已被使用").jsonExit()
    return None


def login_valid(admin: int, **kwargs):
    """
    登陆验证
    :param admin:
    :param kwargs:
    :return:
    """
    username, password = kwargs.get('username'), kwargs.get('password')
    if username is None or username == '':
        return JsonResponse(code = 40002, data = None, message = "username不能为空").jsonExit()
    if password is None or password == '':
        return JsonResponse(code = 40002, data = None, message = "password不能为空").jsonExit()

    user = User.objects(username = username, admin = admin)
    if user.count() == 0:
        return JsonResponse(code = 40003, data = None, message = "用户不存在").jsonExit()
    if user.first().password != password:
        return JsonResponse(code = 40004, data = None, message = "密码错误").jsonExit()
    return JsonResponse(code = 20000, data = user.first().login_to_json(), message = "请求成功").jsonExit()


def user_add_project(**kwargs):
    """
    用户已存在并新增项目
    :param args:
    :param kwargs:
    :return:
    """
    # 1. 获取用户名并判断用户是否存在
    username, phone, projectName = kwargs.get('username'), kwargs.get('phone'), kwargs.get('projectName')
    user = User.objects(username = username)
    projectlist = list(user.first().projectList)
    projectlist.append(projectName)
    user.update(projectList = projectlist)


def user_add_project_id(**kwargs):

    """
    新增用户+projectId
    """

    pass